import { useEffect, useState } from 'react'
import { NavBar, Tabs, ProgressBar, Toast } from 'antd-mobile'
import styles from './Xian.module.css'
import axios from '../../axios'
import { useNavigate } from 'react-router-dom';

export default function Xian() {
    const [sessions, setSessions] = useState<any[]>([])
    const [activeKey, setActiveKey] = useState('')
    const [cart, setCart] = useState<{ [id: number]: number }>({})
    const [cartTotal, setCartTotal] = useState(0)
    const [cartSave, setCartSave] = useState(0)
    const [countdown, setCountdown] = useState('00 : 00 : 00')
    const [stockMap, setStockMap] = useState<{ [id: number]: number }>({})
    // 倒计时和标签
    const [timerLabel, setTimerLabel] = useState('距开始');

    // 获取场次和商品
    useEffect(() => {
        axios.get('http://localhost:3000/jjx/getseckillproducts').then(res => {
            if (res.data && res.data.code === 200) {
                // 过滤掉禁用状态的商品
                const activeProducts = (res.data.data || []).filter((product: any) => 
                    product.status === 'active'
                )
                
                // 将秒杀商品转换为场次格式
                const session = {
                    id: 1,
                    startTime: new Date().toISOString(),
                    endTime: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // 24小时后结束
                    products: activeProducts.map((product: any) => ({
                        id: product.id,
                        name: product.title,
                        spec: product.unit || '件',
                        img: product.image,
                        price: product.currentPrice,
                        originPrice: product.originalPrice,
                        stock: product.stock || 100,
                        sold: product.sales || 0,
                        limit: 5
                    }))
                }
                setSessions([session])
                setActiveKey('1')
                
                // 初始化库存
                const map: { [id: number]: number } = {}
                session.products.forEach((p: any) => {
                    map[p.id] = p.stock
                })
                setStockMap(map)
            }
        }).catch(error => {
            console.error('获取秒杀商品失败:', error)
            Toast.show('获取秒杀商品失败')
        })
    }, [])

    // 当前场次
    const currentSession = sessions.find(s => (s.id + '') === activeKey) || sessions[0] || { products: [] }
    const products = currentSession.products || []

    // 判断当前场次是否已结束
    const now = Date.now();
    const sessionEnded = currentSession && currentSession.endTime && now >= new Date(currentSession.endTime).getTime();

    // 倒计时
    useEffect(() => {
        if (!currentSession) return;
        function updateCountdown() {
            if (!currentSession) return;
            const now = Date.now();
            const startTime = new Date(currentSession.startTime).getTime();
            const endTime = new Date(currentSession.endTime).getTime();
            let diff = 0;
            if (now < startTime) {
                setTimerLabel('距开始');
                diff = startTime - now;
            } else if (now >= startTime && now < endTime) {
                setTimerLabel('距结束');
                diff = endTime - now;
            } else {
                setTimerLabel('已结束');
                diff = 0;
            }
            const h = String(Math.floor(diff / 3600000)).padStart(2, '0');
            const m = String(Math.floor((diff % 3600000) / 60000)).padStart(2, '0');
            const s = String(Math.floor((diff % 60000) / 1000)).padStart(2, '0');
            setCountdown(`${h} : ${m} : ${s}`);
        }
        updateCountdown();
        const timer = setInterval(updateCountdown, 1000);
        return () => clearInterval(timer);
    }, [activeKey, currentSession]);

    // 购物车金额
    useEffect(() => {
        let total = 0, save = 0
        Object.entries(cart).forEach(([id, count]) => {
            const product = sessions.flatMap(s => s.products).find((p: any) => p.id === Number(id))
            if (product) {
                total += product.price * count
                save += ((product.originPrice || product.price) - product.price) * count
            }
        })
        setCartTotal(total)
        setCartSave(save)
    }, [cart, sessions])

    // 加入购物车
    const addToCart = (product: any) => {
        const currentCount = cart[product.id] || 0
        if (currentCount >= product.limit) {
            Toast.show({ content: '已达限购数量', position: 'bottom' })
            return
        }
        if ((stockMap[product.id] || 0) <= 0) {
            Toast.show({ content: '库存不足', position: 'bottom' })
            return
        }
        setCart({ ...cart, [product.id]: currentCount + 1 })
        setStockMap({ ...stockMap, [product.id]: stockMap[product.id] - 1 })
        
        // 添加到 localStorage 购物车
        const cartItem = {
            id: product.id,
            title: product.name,
            image: product.img,
            currentPrice: product.price,
            originalPrice: product.originPrice,
            quantity: 1,
            category: '秒杀商品',
            tags: ['限时秒杀'],
            activity: ['限时秒杀'],
            stock: stockMap[product.id] || 0,
            selected: true
        };
        
        // 从 localStorage 获取现有购物车
        const existingCart = localStorage.getItem('cart');
        let cartItems = existingCart ? JSON.parse(existingCart) : [];
        
        // 检查商品是否已在购物车中
        const existingItemIndex = cartItems.findIndex((item: any) => item.id === product.id);
        
        if (existingItemIndex >= 0) {
            // 如果已存在，增加数量
            cartItems[existingItemIndex].quantity += 1;
        } else {
            // 如果不存在，添加新商品
            cartItems.push(cartItem);
        }
        
        // 保存到 localStorage
        localStorage.setItem('cart', JSON.stringify(cartItems));
        
        Toast.show('已添加到购物车');
        navigate('/app/cars');
    }

    // 下单
    const submitOrder = async () => {
        const orderList = Object.entries(cart).map(([id, count]) => ({ id: Number(id), count }))
        if (orderList.length === 0) {
            Toast.show({ content: '请先选择商品', position: 'bottom' })
            return
        }
        try {
            const res = await axios.post('/jjx/order', { list: orderList })
            if (res.data && res.data.code === 200) {
                Toast.show({ content: '下单成功', position: 'bottom' })
                setCart({})
            } else {
                Toast.show({ content: res.data.msg || '下单失败', position: 'bottom' })
            }
        } catch (e) {
            Toast.show({ content: '下单失败', position: 'bottom' })
        }
    }

    const navigate = useNavigate();

    // 跳转到购物车
    const goToCart = () => {
        navigate('/app/cars');
    };

    // 返回上一页
    const goBack = () => {
        navigate(-1);
    };

    return (
        <div className={styles.pageWrap}>
            <NavBar backArrow={true} onBack={goBack} className={styles.navBar}>限时秒杀</NavBar>
            <div className={styles.tabsContainer}>
                <Tabs
                    className={styles.tabs}
                    activeKey={activeKey}
                    onChange={key => setActiveKey(key)}
                >
                    {sessions.map(item => (
                        <Tabs.Tab
                            key={item.id + ''}
                            title={
                                <div>
                                    <div style={{ color: activeKey === (item.id + '') ? '#ff2d2d' : '#222', fontWeight: activeKey === (item.id + '') ? 700 : 400, fontSize: 16 }}>{item.startTime.slice(11, 16)}</div>
                                    <div style={{ color: activeKey === (item.id + '') ? '#ff2d2d' : '#999', fontSize: 12 }}>{new Date(item.startTime).getTime() < Date.now() && new Date(item.endTime).getTime() > Date.now() ? '抢购中' : (new Date(item.startTime).getTime() > Date.now() ? '即将开始' : '已开抢')}</div>
                                </div>
                            }
                        />
                    ))}
                </Tabs>
            </div>
            <div className={styles.seckillTitle}>{
                products.length > 0
                    ? (
                        currentSession.startTime.slice(11, 16) +
                        (
                            new Date(currentSession.startTime).getTime() < Date.now() && new Date(currentSession.endTime).getTime() > Date.now()
                                ? ' 抢购中'
                                : (
                                    new Date(currentSession.startTime).getTime() > Date.now()
                                        ? ' 即将开始'
                                        : ' 已开抢'
                                )
                        )
                    )
                    : ''
            }</div>
            <div className={styles.seckillTimer}>
                <span className="timer-label">{timerLabel}</span>
                <span className="timer-value">{countdown}</span>
            </div>
            <div className={styles.content}>
                {products.map((product: any) => (
                    <div className={styles.product} key={product.id}>
                        <div className={styles.productImgWrap}>
                            <img src={product.img || '/images/背景图4.jpg'} alt="" />
                        </div>
                        <div className={styles.productInfo}>
                            {/* 第一行：商品名+规格+已抢 */}
                            <div className={styles.productTopRow}>
                                <div style={{ display: 'flex', alignItems: 'center', minWidth: 0 }}>
                                    <span className={styles.productName}>{product.name}</span>
                                    <span className={styles.productSpec}>{product.spec}</span>
                                </div>
                                <span className={styles.productTotal}>已抢{product.sold || 0}份</span>
                            </div>
                            {/* 第二行：进度条 */}
                            <div className={styles.productProgressWrap}>
                                <ProgressBar percent={product.sold && product.stock + (product.sold || 0) > 0 ? Math.round((product.sold / (product.stock + product.sold)) * 100) : 0} style={{ flex: 1, '--fill-color': '#ff4d4f', height: 8, borderRadius: 4 }} />
                            </div>
                            {/* 第三行：已省+限购 */}
                            <div className={styles.productLimitRow}>
                                <div className={styles.productLimitLeft}>
                                    <span className={styles.productSave}>已省{((product.originPrice || product.price) - product.price).toFixed(1)}元</span>
                                    <span className={styles.productLimit}>限购{product.limit}份</span>
                                </div>
                            </div>
                            {/* 第四行：秒杀价+按钮 */}
                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
                                <span className={styles.productPrice}>秒杀价：￥{product.price}</span>
                                <button
                                    className={styles.addCartBtn}
                                    onClick={() => addToCart(product)}
                                    disabled={sessionEnded || (stockMap[product.id] ?? product.stock) <= 0 || (cart[product.id] || 0) >= product.limit}
                                >加入购物车 +</button>
                            </div>
                        </div>
                    </div>
                ))}
            </div>
            {/* 底部购物车栏 */}
            <div className={styles.cartBar}>
                <div className={styles.cartBarLeft} onClick={goToCart} style={{ cursor: 'pointer' }}>
                    <span className={styles.cartIconWrap}>
                        <span role="img" aria-label="cart">🛒</span>
                        {Object.values(cart).reduce((a, b) => a + b, 0) > 0 && <span className={styles.cartCount}>{Object.values(cart).reduce((a, b) => a + b, 0)}</span>}
                    </span>
                    <div>
                        <div className={styles.cartTotal}>总计: ￥{cartTotal.toFixed(2)}</div>
                        <div className={styles.cartSave}>为你节省: ￥{cartSave.toFixed(2)}</div>
                    </div>
                </div>
                <button className={styles.cartSubmitBtn} onClick={submitOrder}>去下单({Object.values(cart).reduce((a, b) => a + b, 0)})</button>
            </div>
        </div>
    );
}